package com.wuyixu.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.wuyixu.domain.Spec;
import com.wuyixu.domain.SpecOption;
import com.wuyixu.service.SpecService;

@Controller
@RequestMapping("spec")
public class SpecController {
	@Reference
	private SpecService specService;
	@RequestMapping("select")
	public String selects(Spec spec,Model model,@RequestParam(defaultValue="1")Integer pageNum,@RequestParam(defaultValue="3")Integer pageSize){
		PageInfo<Spec> info = specService.selects(spec, pageNum, pageSize);
		model.addAttribute("info", info);
		return "spec/list";
	}
	@RequestMapping("toAdd")
	public String toAdd(){
		return "spec/add";
	}
	@RequestMapping("add")
	@ResponseBody
	public String add(Spec spec){
		List<SpecOption> list = spec.getOptions();
		for (int i = list.size()-1; i >=0; i--) {
			SpecOption option = list.get(i);
			if(option.getOptionName()==null ||"".equals(option.getOptionName())){
				list.remove(i);
			}
		}
		int add = specService.add(spec);
		return add>0?"ok":"failed";
	}
	@RequestMapping("del")
	@ResponseBody
	public String del(HttpServletRequest request,@RequestParam(value = "ids[]")  int[] ids) {
		System.out.print("ids is " + ids);
		return specService.delete(ids)>0?"ok":"failed";
	}
	
	/**
	 * 跳转到修改的jsp页面
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("toUpdate")
	public String toUpdate(HttpServletRequest request,int id) {
		Spec spec = specService.getById(id);
		request.setAttribute("spec", spec);
		return "spec/update";
	}
	
	
	/**
	 * 
	 * @param request
	 * @param spec
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public String update(HttpServletRequest request,Spec spec) {
		
		return specService.update(spec)>0?"ok":"failed";
	}
	
	
}
